// sync.task.ts
import { InjectRedis } from '@nestjs-modules/ioredis';
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import Redis from 'ioredis';
import { Video } from 'src/entities/video.entity';
import { VideoHistoryService } from 'src/modules/video-history/video-history.service';
import { Repository } from 'typeorm';
@Injectable()
export class SyncTask {
  private readonly logger = new Logger(SyncTask.name);

  constructor(
    @InjectRedis() private readonly redis: Redis,
    @InjectRepository(Video)
    private readonly videoRepo: Repository<Video>,
    private videoHistoryService: VideoHistoryService
  ) {}

  @Cron(CronExpression.EVERY_10_MINUTES) // 每10分钟执行
  async syncLikes() {
    // 获取待同步的video_id
    const videoIds = await this.redis.smembers('sync_queue');
    if (videoIds.length === 0) return;

    // 批量处理每个视频
    for (const videoId of videoIds) {
      // 1. 同步点赞数
      const likeCount = await this.redis.hget('video_likes', videoId);
      await this.videoRepo.update(
        { video_id: Number(videoId) },
        { likes_count: parseInt(likeCount) || 0 },
      );

      // 2. 同步用户点赞关系（可选，根据需求实现）
      // ... 对比Redis和MySQL差异，增量更新
    }

    // 清空同步队列
    await this.redis.del('sync_queue');

    this.logger.log(`Synced ${videoIds.length} videos(同步视频的点赞数)`);
  }

  @Cron('0 3 * * *') // 每天凌晨3点执行
  async handleCleanup() {
    this.logger.debug('Cleaning up old view histories...');
    await this.videoHistoryService.cleanupOldRecords();
    this.logger.debug('View history cleanup completed');
  }
}
